package com.example.mybrowser;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;

public class MobileService extends Thread
{
	ResourceSocketThread[] resthread;
	public MainActivity mainActivity;
	public MobileCache mobileCache;
	public MyHandler handler;
	public String Android_ID;
	public MobileService(ResourceSocketThread[] _resthread, MobileCache _mobileCache, MainActivity _mainActivity, MyHandler _handler, String _Android_ID)
	{
		handler = _handler;
		resthread = _resthread;
		mobileCache = _mobileCache;
		mainActivity = _mainActivity;
		Android_ID = _Android_ID;
	}
	public int webStateBefore;
	@Override
	public void run()
	{
		resthread = new ResourceSocketThread[1000];
		webStateBefore = -1;
		ConnectivityManager conMan = (ConnectivityManager) mainActivity.getSystemService(Context.CONNECTIVITY_SERVICE);

		try {
			ServerSocket socketManager = new ServerSocket(8080);
			
			int i;
			for (i=0;;i=(i+1)%1000)
			{
				
				Socket socket = socketManager.accept();
				NetworkInfo[] info = conMan.getAllNetworkInfo();

				int webState=0; //0 for no, 1 for mobile, 2 for wifi
				for (i=0;i<info.length;i++)
				{
					if (info[i].getState() == NetworkInfo.State.CONNECTED) 
					{ 
						webState = 1; 
					} 
				}
				
				if (webStateBefore != webState)
				{
					webStateBefore = webState;
					handler.obtainMessage(0, webState+"").sendToTarget();
				}
				
				resthread[i] = new ResourceSocketThread(socket, handler, mobileCache, webState, Android_ID);
				resthread[i].start();
			}
		}				

		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			

	}
}
